import Vue from "vue";
import VueRouter from "vue-router";
import axios from "axios";
import { Message, MessageBox } from "element-ui";
// 进度条
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import store from "@/store/index";
import util from "@/libs/util.js";
// 路由数据
import routes from "./routes";
import { dynamicRoutes, frameInRoutes } from "@/router/routes";

Vue.use(VueRouter);

// 导出路由 在 main.js 里使用
const router = new VueRouter({
  routes,
});

const noRedirectPaths = dynamicRoutes.map((item) => item.path); //点击顶部模块名，不需要直接重定向的路径

/**
 * 路由拦截
 * 权限验证
 */
router.beforeEach((to, from, next) => {
  NProgress.start();
  const token = util.cookies.get("token");
  if (to.matched.some((r) => r.meta.auth)) {
    if (token && token !== "undefined") {
      const remoteMenu = store.state.d2admin.menu.remoteMenu;
      if (remoteMenu && remoteMenu.length === 0) {
        util.cookies.remove("token");
        util.cookies.remove("uuid");
        MessageBox.alert("您的账号还未被授权，请联系企业管理员授权使用！", "提示", {
          confirmButtonText: "确定",
          type: "warning",
        });
        store.dispatch("d2admin/account/logout").then((res) => {
          next({ name: "login" });
          NProgress.done();
        });
      } else if (remoteMenu && remoteMenu.length !== 0) {
        const keepAlive = store.state.d2admin.page.keepAlive;
        if (to.params.isTabClick) {
          next();
        } else if (keepAlive.length > 19) {
          Message({
            type: "warning",
            message: "您打开的Tab页太多，请先关闭一部分Tab页！",
          });
        } else {
          if (noRedirectPaths.includes(to.path)) {
            store.dispatch("d2admin/menu/switchAsideMenu", to.path).then(() => {
              NProgress.done();
            });
          } else {
            next();
            NProgress.done();
          }
        }
      } else {
        store
          .dispatch("d2admin/menu/getRemoteMenu")
          .then((res) => {
            if (res.length === 0) {
              util.cookies.remove("token");
              util.cookies.remove("uuid");
              MessageBox.alert("您的账号还未被授权，请联系企业管理员授权使用！", "提示", {
                confirmButtonText: "确定",
                type: "warning",
              });
              store.dispatch("d2admin/account/logout").then((res) => {
                next({ name: "login" });
                NProgress.done();
              });
            } else {
              if (noRedirectPaths.includes(to.path)) {
                store.dispatch("d2admin/menu/switchAsideMenu", to.path).then(() => {
                  next({ name: "index" });
                  NProgress.done();
                });
              } else {
                next();
                NProgress.done();
              }
            }
          })
          .catch((e) => {
            console.log(e)
            store.dispatch("d2admin/account/logout").then((res) => {
              next({ name: "login" });
              NProgress.done();
            });
          });
      }
    } else {
      store.dispatch("d2admin/account/logout").then((res) => {
        next({ name: "login" });
        NProgress.done();
      });
      // next();
      // NProgress.done();
    }
  } else {
    if (token && token !== "undefined") {
      if (to.path === "/registerPerson" || to.path === "/realName" || to.path === "/partner" || to.path === "/enterprise") {
        next();
        NProgress.done();
        return;
      }
      if (to.path === "/selectAccount") {
        next({ path: "/" });
        NProgress.done();
        return;
      }
      if (to.path === "/login") {
        if (from.path === "/registerPerson") {
          util.cookies.remove("token");
          util.cookies.remove("uuid");
          store.commit("d2admin/menu/remoteMenuSet", null);
          next({ path: "/registerPerson" });
        } else if (from.path === "/register") {
          util.cookies.remove("token");
          util.cookies.remove("uuid");
          store.commit("d2admin/menu/remoteMenuSet", null);
          next({ path: "/login" });
        } else {
          next({ path: "/" }); // 直接进入首页 ，相当于免登陆
        }
        NProgress.done();
        return;
      }
      next();
      NProgress.done();
    } else {
      next();
      NProgress.done();
    }
  }
});

// 心跳句柄
let timerCount = 0;
let timerHandle = null;
let heartBeatFn = () => {
  axios({
    url: "/api/api",
    method: "post",
    timeout: 30000,
    data: {
      head: {
        timestamp: new Date().getTime(),
        transCode: "U2000106",
      },
    },
  })
    .then(() => {
      timerCount = 0;
      console.log("心跳成功");
    })
    .catch((error) => {
      if (timerCount <= 4) {
        timerCount++;
        setTimeout(heartBeatFn, 1000);
      }
      console.log("心跳检测失败", error);
    });
};

router.afterEach((to) => {
  NProgress.done();
  // 多页控制 打开新的页面
  store.dispatch("d2admin/page/open", to);
  // 更改标题
  util.title(to.meta.title);
  let filterList = [ "login", "purchaseTemplate", "purchaseStockTemplate", "saleTemplate", "saleStockTemplate" ];
  // 心跳处理
  if (filterList.indexOf(to.name) >= 0 || util.cookies.get("token") === undefined) {
    clearInterval(timerHandle);
    timerHandle = null;
  } else if (timerHandle === null) {
    timerHandle = setInterval(heartBeatFn, 1000 * 60 * 2);
  }
});

export default router;
